<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use App\Util\SqlServerUtil;
use Closure;
use Illuminate\Support\Facades\Session;

class AdminAuth  
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
	public function __construct(Request $request){
		$DB = $request->get("db") ? $request->get("db") : env('DB_DATABASE_NAME');
		$serverConfig = [ "UID" => env("DB_USERNAME"), "PWD" => env("DB_PASSWORD"), "Database" => $DB];
		$sqlCon = sqlsrv_connect(env("DB_HOST"), $serverConfig);
		//数据库账套选择
		$this->DB = $DB;
		if($sqlCon){
			return $this->SqlServer =$sqlCon;
		}
		return false;
	}
	
	public function handle($request, Closure $next)
	{
		
		if(is_null(session('adminAuth'))) return redirect(url('login'));
		$id = session()->get('adminAuth');
		$sql="select last_session from gz_admin where id='{$id}'";
		$res = SqlServerUtil::exec($this->SqlServer, $sql,2);
		if(Session::getId() != $res['last_session'] ){
			session(['adminAuth'=>null]); //清除session
			
			return redirect(url('login'));
		}
		
		$response = $next($request);
		$response->header('Access-Control-Allow-Origin', '*'); //允许所有资源跨域
		$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json , X-Auth-Token');//允许通过的响应报头
		$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');//允许的请求方法
		$response->header('Access-Control-Expose-Headers', 'Authorization');//允许axios获取响应头中的Authorization
		$response->header('Allow', 'GET, POST, PATCH, PUT, OPTIONS, delete');//允许的请求方法
		$response->header('Access-Control-Allow-Credentials', 'true');//运行客户端携带证书式访问
		
		return $response;
	}
	
	
}
